﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DBConnection
{
    public class UsersDAO
    {
        public static List<String> GetAllUsers(TwitterDataContext context)
        {
            List<string> users =
                (from u in context.Users
                    select u.Name
                ).ToList();
            return users;
        }

        public static bool RegisterUser(string name, string cachedPassword, 
            TwitterDataContext context)
        {
            if (GetUserID(name, context) != null)
            {
                return false;
            }

            User newUser = new User();
            newUser.Name = name;
            newUser.Password = cachedPassword;
            context.Users.InsertOnSubmit(newUser);
            context.SubmitChanges();
            return true;
        }

        public static int? GetUserID(string name, TwitterDataContext context)
        {
            var user =
                from u in context.Users
                where u.Name == name
                select u.UserID;

            if (user.ToList().Count == 0)
            {
                return null;
            }
            return user.ToList()[0];
        }

        public static bool IsCorrectLogin(string name, string cachedPassword,
            TwitterDataContext context)
        {
            var user =
                from u in context.Users
                where u.Name == name && u.Password == cachedPassword
                select u;

            if (user.ToList().Count == 1)
            {
                return true;
            }
            return false;
        }

        //public static void ChangePassword(string name, string newCachedPassword,
        //    TwitterDataContext context)
        //{
        //    User user =
        //        (from u in context.Users
        //        where u.Name == name
        //        select u).FirstOrDefault();
        //    user.Password = newCachedPassword;
        //    context.SubmitChanges();
        //}
    }
}
